import React, { useState, useEffect } from 'react'
import {
  Modal,
  Form,
  Radio,
  Checkbox,
  Input,
  Button,
  Space,
  Progress,
  Typography,
  Divider,
  Card,
  Row,
  Col,
  Alert,
  message
} from 'antd'
import {
  FileTextOutlined,
  FilePdfOutlined,
  FileExcelOutlined,
  DownloadOutlined,
  SettingOutlined,
  InfoCircleOutlined
} from '@ant-design/icons'
import { StoryboardData } from '../../../types/document'
import { ExportType, ExportOptions, ExportProgress } from './types'
import { StoryboardExportManager } from './StoryboardExportManager'

const { Title, Text } = Typography

export interface StoryboardExportDialogProps {
  visible: boolean
  storyboardData: StoryboardData
  projectTitle?: string
  onClose: () => void
}

/**
 * 分镜导出对话框
 * 提供完整的导出选项和进度显示
 */
export const StoryboardExportDialog: React.FC<StoryboardExportDialogProps> = ({
  visible,
  storyboardData,
  projectTitle = '分镜脚本',
  onClose
}) => {
  const [form] = Form.useForm()
  const [exportManager] = useState(() => new StoryboardExportManager())
  const [exporting, setExporting] = useState(false)
  const [exportProgress, setExportProgress] = useState<ExportProgress | null>(null)
  const [selectedScenes, setSelectedScenes] = useState<string[]>([])
  const [estimatedSize, setEstimatedSize] = useState<string>('')
  
  const scenes = storyboardData.scenes || []
  
  // 初始化表单默认值
  useEffect(() => {
    if (visible) {
      form.setFieldsValue({
        type: ExportType.PDF,
        includeAll: true,
        includeThumbnails: false,
        includeTechnicalParams: true,
        includeStatistics: true,
        includeNotes: true,
        pageSize: 'A4',
        orientation: 'portrait',
        fileName: '',
        quality: 'high'
      })
      
      setSelectedScenes(scenes.map(scene => scene.id))
      updateEstimatedSize(ExportType.PDF, true, scenes.map(scene => scene.id))
    }
  }, [visible, scenes, form])
  
  // 更新估算文件大小
  const updateEstimatedSize = (type: ExportType, includeAll: boolean, sceneIds: string[]) => {
    const options: ExportOptions = {
      type,
      includeAll,
      selectedSceneIds: sceneIds,
      includeThumbnails: false,
      includeTechnicalParams: true,
      includeStatistics: true,
      includeNotes: true
    }
    
    const estimate = exportManager.estimateFileSize(storyboardData, options)
    setEstimatedSize(estimate.description)
  }
  
  // 处理导出类型变化
  const handleTypeChange = (type: ExportType) => {
    const includeAll = form.getFieldValue('includeAll')
    updateEstimatedSize(type, includeAll, selectedScenes)
  }
  
  // 处理导出范围变化
  const handleScopeChange = (includeAll: boolean) => {
    const type = form.getFieldValue('type')
    const sceneIds = includeAll ? scenes.map(scene => scene.id) : selectedScenes
    updateEstimatedSize(type, includeAll, sceneIds)
  }
  
  // 处理场景选择变化
  const handleSceneSelectionChange = (sceneIds: string[]) => {
    setSelectedScenes(sceneIds)
    const type = form.getFieldValue('type')
    const includeAll = form.getFieldValue('includeAll')
    if (!includeAll) {
      updateEstimatedSize(type, false, sceneIds)
    }
  }
  
  // 执行导出
  const handleExport = async () => {
    try {
      const values = await form.validateFields()
      
      setExporting(true)
      setExportProgress(null)
      
      const options: ExportOptions = {
        ...values,
        selectedSceneIds: values.includeAll ? undefined : selectedScenes
      }
      
      // 验证选项
      const validation = exportManager.validateOptions(options)
      if (!validation.valid) {
        message.error(validation.errors.join(', '))
        setExporting(false)
        return
      }
      
      const result = await exportManager.exportStoryboard(
        storyboardData,
        options,
        projectTitle,
        setExportProgress
      )
      
      if (result.success) {
        message.success(`导出成功！文件大小: ${(result.fileSize! / 1024).toFixed(1)} KB`)
        onClose()
      } else {
        message.error(`导出失败: ${result.error}`)
      }
      
    } catch (error) {
      console.error('导出失败:', error)
      message.error('导出失败，请重试')
    } finally {
      setExporting(false)
      setExportProgress(null)
    }
  }
  
  // 渲染格式选择
  const renderFormatSelection = () => (
    <Form.Item name="type" label="导出格式">
      <Radio.Group onChange={(e) => handleTypeChange(e.target.value)}>
        <Space direction="vertical">
          <Radio value={ExportType.PDF}>
            <Space>
              <FilePdfOutlined style={{ color: '#ff4d4f' }} />
              <span>PDF 格式</span>
              <Text type="secondary">专业分镜脚本，适合打印</Text>
            </Space>
          </Radio>
          <Radio value={ExportType.EXCEL}>
            <Space>
              <FileExcelOutlined style={{ color: '#52c41a' }} />
              <span>Excel 表格</span>
              <Text type="secondary">结构化数据，便于编辑</Text>
            </Space>
          </Radio>
          <Radio value={ExportType.TEXT}>
            <Space>
              <FileTextOutlined style={{ color: '#1890ff' }} />
              <span>纯文本</span>
              <Text type="secondary">简洁格式，快速查看</Text>
            </Space>
          </Radio>
          <Radio value={ExportType.MARKDOWN}>
            <Space>
              <FileTextOutlined style={{ color: '#722ed1' }} />
              <span>Markdown</span>
              <Text type="secondary">支持格式化的文本</Text>
            </Space>
          </Radio>
        </Space>
      </Radio.Group>
    </Form.Item>
  )
  
  // 渲染导出范围
  const renderExportScope = () => (
    <Form.Item name="includeAll" label="导出范围">
      <Radio.Group onChange={(e) => handleScopeChange(e.target.value)}>
        <Radio value={true}>导出全部场景 ({scenes.length}个)</Radio>
        <Radio value={false}>导出选中场景</Radio>
      </Radio.Group>
    </Form.Item>
  )
  
  // 渲染场景选择
  const renderSceneSelection = () => {
    const includeAll = Form.useWatch('includeAll', form)
    
    if (includeAll) return null
    
    return (
      <Form.Item label="选择场景">
        <Checkbox.Group
          value={selectedScenes}
          onChange={handleSceneSelectionChange}
        >
          <Row>
            {scenes.map(scene => (
              <Col span={12} key={scene.id}>
                <Checkbox value={scene.id}>
                  {scene.order + 1}. {scene.title}
                </Checkbox>
              </Col>
            ))}
          </Row>
        </Checkbox.Group>
      </Form.Item>
    )
  }
  
  // 渲染导出选项
  const renderExportOptions = () => {
    const exportType = Form.useWatch('type', form)
    const supportedOptions = exportManager.getSupportedOptions(exportType)
    
    return (
      <Card title="导出选项" size="small">
        <Space direction="vertical" style={{ width: '100%' }}>
          {supportedOptions.includeThumbnails && (
            <Form.Item name="includeThumbnails" valuePropName="checked">
              <Checkbox>包含缩略图</Checkbox>
            </Form.Item>
          )}
          
          {supportedOptions.includeTechnicalParams && (
            <Form.Item name="includeTechnicalParams" valuePropName="checked">
              <Checkbox>包含技术参数</Checkbox>
            </Form.Item>
          )}
          
          {supportedOptions.includeStatistics && (
            <Form.Item name="includeStatistics" valuePropName="checked">
              <Checkbox>包含统计信息</Checkbox>
            </Form.Item>
          )}
          
          {supportedOptions.includeNotes && (
            <Form.Item name="includeNotes" valuePropName="checked">
              <Checkbox>包含制作备注</Checkbox>
            </Form.Item>
          )}
          
          {exportType === ExportType.PDF && (
            <>
              <Form.Item name="pageSize" label="页面大小">
                <Radio.Group>
                  <Radio value="A4">A4</Radio>
                  <Radio value="Letter">Letter</Radio>
                  <Radio value="A3">A3</Radio>
                </Radio.Group>
              </Form.Item>
              
              <Form.Item name="orientation" label="页面方向">
                <Radio.Group>
                  <Radio value="portrait">竖向</Radio>
                  <Radio value="landscape">横向</Radio>
                </Radio.Group>
              </Form.Item>
            </>
          )}
          
          <Form.Item name="fileName" label="自定义文件名">
            <Input 
              placeholder="留空使用默认文件名" 
              addonAfter={`.${exportType}`}
            />
          </Form.Item>
        </Space>
      </Card>
    )
  }
  
  // 渲染进度显示
  const renderProgress = () => {
    if (!exportProgress) return null
    
    return (
      <Card>
        <Space direction="vertical" style={{ width: '100%' }}>
          <Progress 
            percent={exportProgress.progress} 
            status={exportProgress.stage === 'error' ? 'exception' : 'active'}
          />
          <Text>{exportProgress.message}</Text>
          {exportProgress.error && (
            <Alert message={exportProgress.error} type="error" />
          )}
        </Space>
      </Card>
    )
  }
  
  return (
    <Modal
      title={
        <Space>
          <DownloadOutlined />
          导出分镜脚本
        </Space>
      }
      open={visible}
      onCancel={onClose}
      width={800}
      footer={
        <Space>
          <Button onClick={onClose}>取消</Button>
          <Button
            type="primary"
            icon={<DownloadOutlined />}
            loading={exporting}
            onClick={handleExport}
            disabled={exporting}
          >
            {exporting ? '导出中...' : '开始导出'}
          </Button>
        </Space>
      }
    >
      <Form form={form} layout="vertical">
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          {/* 项目信息 */}
          <Alert
            message={
              <Space>
                <InfoCircleOutlined />
                <span>项目: {projectTitle}</span>
                <span>场景数: {scenes.length}</span>
                <span>预估大小: {estimatedSize}</span>
              </Space>
            }
            type="info"
          />
          
          {/* 导出进度 */}
          {exporting && renderProgress()}
          
          {/* 格式选择 */}
          {renderFormatSelection()}
          
          <Divider />
          
          {/* 导出范围 */}
          {renderExportScope()}
          
          {/* 场景选择 */}
          {renderSceneSelection()}
          
          <Divider />
          
          {/* 导出选项 */}
          {renderExportOptions()}
        </Space>
      </Form>
    </Modal>
  )
}